from pynput import keyboard
from pynput.mouse import Controller as mouseControl
from pynput.keyboard import Controller as keyboardControl
from pynput.keyboard import Listener
from pynput.mouse import Listener as MouseListener
import json
import sys
import pyautogui
import time

stop_program = False  # 设置一个标志用于停止循环
timeStruct = time.localtime(int(time.time()))  # 获得当前时间时间戳后转化为本地时间
strTime = time.strftime("%Y-%m-%d %H:%M:%S", timeStruct)  # 日期格式 2022-08-23 07:26:21


# 鼠标动作
def on_move(x, y):
    mouse_action = {'x': x, 'y': y, 'type': 'move'}
    mouse_key_actions.append(mouse_action)
    log_file.write(f"{strTime} 鼠标操作: 移动到({x}, {y})\n")


def on_click(x, y, button, pressed):
    if pressed:
        mouse_action = {'x': x, 'y': y, 'type': 'press', 'button': f'{button.name}'}
        mouse_key_actions.append(mouse_action)
        log_file.write(f"{strTime} 鼠标操作: 按下，位置({x}, {y}), 按钮: {button.name}\n")
    else:
        mouse_action = {'x': x, 'y': y, 'type': 'release', 'button': f'{button.name}'}
        mouse_key_actions.append(mouse_action)
        log_file.write(f"{strTime} 鼠标操作: 松开，位置({x}, {y}), 按钮: {button.name}\n")


def on_scroll(x, y, dx, dy):
    mouse_action = {'x': x, 'y': y, 'type': 'scroll', 'dx': dx, 'dy': dy}
    mouse_key_actions.append(mouse_action)
    log_file.write(f"{strTime} 鼠标操作: 滚动，位置({x}, {y}), 滚动方向: ({dx}, {dy})\n")

# 键盘操作
def on_press(key):
    try:
        key_action = {'key': key.char, 'type': 'pkey'}
    except AttributeError:
        key_action = {'key': f'{key.name}', 'type': 'pspecial key'}
    mouse_key_actions.append(key_action)
    log_file.write(f"{strTime} 键盘事件: 按键: {key_action['key']}\n")
    if key == keyboard.Key.num_lock:
        with open(file_name, "w") as f:
            json.dump(mouse_key_actions, f)
        current_time = time.time()
        elapsed_time = current_time - start_time
        print(f'\n此次录入使用时间为{elapsed_time}秒')
        time.sleep(0.1)
        keyboard_listener.stop()
        mouse_listener.stop()


def on_release(key):
    try:
        key_action = {'key': key.char, 'type': 'rkey'}
    except AttributeError:
        key_action = {'key': f'{key.name}', 'type': 'rspecial key'}
    mouse_key_actions.append(key_action)
    log_file.write(f"{strTime} 键盘事件: 松键: {key_action['key']}\n")


def on_stop(key):
    global stop_program  # 声明为全局变量
    if key == keyboard.Key.esc:
        print('\nESC key pressed! Program will stop in this time over.')
        keyboard_listen.stop()
        stop_program = True  # 设置标志为True

def on_replay():
    for action in log_data:
        if action['type'] == 'move':
            # 移动鼠标
            # time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.moveTo(action['x'], action['y'])
        elif action['type'] == 'pspecial key' and action['key'] == 'cmd':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown('win')
        elif action['type'] == 'rspecial key' and action['key'] == 'cmd':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp('win')
        elif action['type'] == 'pspecial key' and action['key'] == 'ctrl_l':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown('ctrl')
        elif action['type'] == 'rspecial key' and action['key'] == 'ctrl_l':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp('ctrl')
        elif action['type'] == 'pspecial key' and action['key'] == 'alt_l':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown('alt')
        elif action['type'] == 'rspecial key' and action['key'] == 'alt_l':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp('alt')
        elif action['type'] == 'pspecial key' and action['key'] == 'caps_lock':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown('capslock')
        elif action['type'] == 'rspecial key' and action['key'] == 'caps_lock':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp('capslock')
        elif action['type'] == 'press':
            # 点击鼠标
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.mouseDown(action['x'], action['y'], button=action['button'])
        elif action['type'] == 'release':
            # 点击鼠标
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.mouseUp(action['x'], action['y'], button=action['button'])
        elif action['type'] == 'scroll':
            # 滚动鼠标滚轮
            time.sleep(0.1)  # 可根据需要调整延时时间
            mouse.scroll(action['x'], action['dy'] * 1)
        elif action['type'] == 'pkey':
            # 按下键盘键
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown(action['key'])
        elif action['type'] == 'pspecial key':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyDown(action['key'])
        elif action['type'] == 'rkey':
            # 按下键盘键
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp(action['key'])
        elif action['type'] == 'rspecial key':
            # 按下特殊按键（如功能键、导航键等）
            time.sleep(0.1)  # 可根据需要调整延时时间
            pyautogui.keyUp(action['key'])
# 选择相应的模式1
print('请选择模式 (1 录制，2 回放，q退出):', end=" ")
a = input()

if a == '1':

    # 创建一个文件来记录作
    log_file = open("mouse_keyboard.txt", "w")

    # 记录鼠标和键盘的操作
    mouse_key_actions = []

    # 将鼠标操作记录保存到JSON文件中
    file_name = f"mouse_keyboard_{int(time.time())}.json"

    # 开始监听鼠标事件
    mouse_listener = MouseListener(on_click=on_click, on_move=on_move, on_scroll=on_scroll)
    mouse_listener.start()

    # 开始监听键盘事件
    keyboard_listener = Listener(on_press=on_press, on_release=on_release)
    keyboard_listener.start()

    start_time = time.time()

    # 等待监听器结束
    mouse_listener.join()
    keyboard_listener.join()


elif a == '2':
    pyautogui.FAILSAFE = False
    mouse = mouseControl()  # 鼠标控制器
    # key = keyboardControl() # 键盘控制器

    keyboard_listen = Listener(on_press=on_stop)
    keyboard_listen.start()

    # 打开日志文件并读取数据
    print('请输入要回放的脚本文件全名:', end=' ')
    m_k_name = input()
    with open(m_k_name, "r") as file:
        log_data = json.load(file)

    print('请选择回放模式(1时间段,2次数):', end=' ')
    b = input()
    if b == '1':

        # 设置程序运行时间（单位：秒）
        print('请输入运行时间（单位：秒）:', end=' ')
        run_time = int(input())

        # 开始计时
        start_time = time.time()
        elapsed_time = 0
        cishu = 0
        # 运行程序
        while elapsed_time <= run_time and not stop_program:
            # 执行程序代码
            on_replay()
            cishu += 1
            current_time = time.time()
            elapsed_time = current_time - start_time
        print(f'\n此次运行时间为{elapsed_time}秒')
        if stop_program:
            print('Program stopped.')
        else:
            print(f'Program finished {cishu} times.')

    elif b == '2':
        # 设置程序运行时间（单位：秒）
        print('请输入运行次数:', end=' ')
        run_number = int(input())
        # 开始计时
        start_time = time.time()
        i = 0
        while i < run_number and not stop_program:
            # 执行程序代码
            i = i + 1
            on_replay()
        current_time = time.time()
        elapsed_time = current_time - start_time
        print(f'\n此次运行时间为{elapsed_time}秒')
        if stop_program:
            print('Program stopped.')
        else:
            print(f'Program finished {i} times.')

elif a == 'q':
    sys.exit()
